package com.ruoyi.project.cms.product.service;

import com.ruoyi.common.constant.ProductConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.cms.product.domain.ProductSeries;
import com.ruoyi.project.cms.product.mapper.ProductMapper;
import com.ruoyi.project.cms.product.mapper.SeriesMapper;
import com.ruoyi.project.system.post.domain.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @CreateTime 2020/5/17 22:59
 */
@Service
public class SeriesServiceImpl implements SeriesService {
    @Autowired
    private SeriesMapper seriesMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 增改查中表单下拉框
     */
    @Override
    public List<ProductSeries> findAllName() {
        return seriesMapper.selectAllName();
    }

    /**
     * 查询全部的产品系列信息
     */
    @Override
    public List<ProductSeries> findAll(ProductSeries series) {
        return seriesMapper.selectAll(series);
    }

    /**
     * 校验名称是否唯一
     */
    @Override
    public String checkSeriesNameUnique(ProductSeries series) {
        Long seriesId = StringUtils.isNull(series.getSeriesId()) ? -1L : series.getSeriesId();
        ProductSeries info = seriesMapper.checkSeriesNameUnique(series.getSeriesName());
        if (StringUtils.isNotNull(info) && info.getSeriesId().longValue() != seriesId.longValue())
        {
            return ProductConstants.PRODUCT_SERIES_NAME_NOT_UNIQUE;
        }
        return ProductConstants.PRODUCT_SERIES_NAME_UNIQUE;
    }

    /**
     * 添加系列信息
     */
    @Override
    public int addSeries(ProductSeries series) {
        return seriesMapper.insertSeries(series);
    }

    /**
     * 根据ID查询
     */
    @Override
    public ProductSeries findSeriesById(Long seriesId) {
        return seriesMapper.selectSeriesById(seriesId);
    }

    /**
     * 修改系列信息
     */
    @Override
    public int changeSeries(ProductSeries series) {
        return seriesMapper.updateSeries(series);
    }

    /**
     * 批量删除系列信息
     */
    @Override
    public int removeSeriesByIds(String ids) throws BusinessException
    {
        Long[] seriesIds = Convert.toLongArray(ids);
        for (Long seriesId : seriesIds)
        {
            ProductSeries series = findSeriesById(seriesId);
            //当前业务层中这里循环校验的是 准备删除的系列名称 是否 已经在产品中进行使用了 给与一个参数1
            if (productMapper.selectIsUsing(seriesId,1) > 0)
            {
                throw new BusinessException(String.format("%1$s:该系列正在使用,不能删除", series.getSeriesName()));
            }
        }
        return seriesMapper.deleteSeriesByIds(seriesIds);
    }
}
